package fr.reseau.echec;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Serveur implements Runnable {
	
	private static ServerSocket server = null;
	private static Socket socket = null;
	private static int numeroPort =0;
 
	public Serveur() {
	}
	
    public void run() {
    	numeroPort = choixPort();
    	try {
			server = new ServerSocket(numeroPort);
		} 
    	catch (IOException e2) {
    		e2.printStackTrace();
		}
    	try {
			System.out.println("Communiquez a votre adversaire l'adresse IP" + InetAddress.getLocalHost());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		
    	try {
			server.setSoTimeout(30000);
		}
    	catch (SocketException e) {
			e.printStackTrace();
		}
    	
		try {
				socket = server.accept();
				System.out.println("Operation realise avec succes !");
		}
		catch (InterruptedIOException e) {
			System.err.println("Timed Out (60 sec)!");	
		} 
		catch (BindException e) {}
		catch (IOException e)
		{
			System.err.println("Erreur de connexion");
		}
		
		
		finally {
			if (socket !=null)
				try {
					socket.close();
				} 
				catch (IOException e) {
					e.printStackTrace();
				}
			if (server != null)
				try {
					server.close();
				} 
				catch (IOException e) {
					e.printStackTrace();
				}
		}
	}
    
    public static int choixPort()
    {
    	Scanner sc = new Scanner(System.in);
    	int numPort;
    	do {
    		System.out.print ("Choisir votre numero de port : ");
    		numPort = sc.nextInt();
    	} while (numPort <= 0);
    	return numPort;
    }
    
    public static ServerSocket getServer() {
		return server;
	}

	public static void setServer(ServerSocket server) {
		Serveur.server = server;
	}

	public static Socket getSocket() {
		return socket;
	}

	public static void setSocket(Socket socket) {
		Serveur.socket = socket;
	}

	public int getNumeroPort() {
		return numeroPort;
	}

	public void setNumeroPort(int numeroPort) {
		Serveur.numeroPort = numeroPort;
	}
}